﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using EFFC.Net.Event;
using EFFC.Net.Common;
using EFFC.Net.Exceptions;
using System.Web;
using EFFC.Net.WebBuilder.WebManage;
using EFFC.Net.ControlLibary.Input;
using EFFC.Net.Interface;
using EFFC.Net.Data.Base;
using System.Threading;
using EFFC.Net.Parameters;
using EFFC.Net.Returns;
using EFFC.Net.WebBuilder.Parameters;
using EFFC.Net.ControlLibary.Web.GridViewCustom;
using EFFC.Net.WebBuilder.WebLogic;

namespace EFFC.Net.WebBuilder.WebPage
{
    public abstract class WebPageBase : Page
    {
        bool _isReady = false;
        protected Dictionary<string, Control> _controls_DataMap = new Dictionary<string, Control>();
        protected Dictionary<string, Control> _controls_Permission = new Dictionary<string, Control>();
        public WebPageBase()
        {
            _isReady = false;
        }
        /// <summary>
        /// Request已经重新定义，不放开使用
        /// </summary>
        public new HttpRequest Request
        {
            get
            {
                if (!_isReady)
                    return base.Request;
                else
                    return null;
            }
        }
        /// <summary>
        /// Response已经重新定义，不放开使用
        /// </summary>
        public HttpResponse Reponse
        {
            get
            {
                if (!_isReady)
                    return base.Response;
                else
                    return null;
            }
        }

        /// <summary>
        /// Response已经重新定义，不放开使用
        /// </summary>
        protected HttpResponse BaseReponse
        {
            get
            {
                return base.Response;
            }
        }
        /// <summary>
        /// 此属性提供原Page的Request以供做PageBase使用，继承类请将该方法屏蔽
        /// </summary>
        protected HttpRequest BaseRequest
        {
            get
            {
                return base.Request;
            }
        }
        /// <summary>
        /// ClientScript已经重新定义，不放开使用
        /// </summary>
        private new ClientScriptManager ClientScript
        {
            get
            {
                if (!_isReady)
                    return base.ClientScript;
                else
                    return null;
            }
        }
        /// <summary>
        /// RegisterClientScriptBlock不再放开使用
        /// </summary>
        /// <param name="key"></param>
        /// <param name="script"></param>
        private new void RegisterClientScriptBlock(string key, string script)
        {
            base.ClientScript.RegisterClientScriptBlock(this.GetType(), key, script, true);
        }
        /// <summary>
        /// RegisterStartupScript不再放开使用
        /// </summary>
        /// <param name="key"></param>
        /// <param name="script"></param>
        private new void RegisterStartupScript(string key, string script)
        {
            base.ClientScript.RegisterStartupScript(this.GetType(), key, script, true);
        }

        /// <summary>
        /// 获取Request的参数
        /// </summary>
        public Dictionary<string, string> RequestParameters
        {
            get
            {
                return (Dictionary<string, string>)ViewState[this.ClientID + "_RequestStrings"];
            }
        }
        /// <summary>
        /// 连接跳转
        /// </summary>
        /// <param name="url"></param>
        public void Redirect(string url)
        {
            if (GlobalCommon.SecurityStrategy.IsValidUrl(url))
            {
                Response.Redirect(url,false);
            }
            else
            {
                throw new BizException(url + ":Is not valid URL");
            }
        }
        /// <summary>
        /// 连接跳转
        /// </summary>
        /// <param name="url"></param>
        /// <param name="endResponse">是否结束Response</param>
        public void Redirect(string url,bool endResponse)
        {
            if (GlobalCommon.SecurityStrategy.IsValidUrl(url))
            {
                Response.Redirect(url, endResponse);
            }
            else
            {
                throw new BizException(url + ":Is not valid URL");
            }
        }

        protected sealed override void OnLoad(EventArgs e)
        {
            try
            {
                //屏蔽Request的开关
                _isReady = true;
                //获取request参数
                Dictionary<string, string> _requeststrings = new Dictionary<string, string>();
                foreach (string s in base.Request.QueryString.Keys)
                {
                    _requeststrings.Add(s, HttpUtility.HtmlEncode(BaseRequest[s]));
                }
                ViewState.Remove(this.ClientID + "_RequestStrings");
                ViewState.Add(this.ClientID + "_RequestStrings", _requeststrings);

                FindControls(this);
                OnPageLoad();
                base.OnLoad(e);
            }
            catch (Exception ex)
            {
                GlobalCommon.ExceptionProcessor.DoProcess(ex);
            }
        }

        protected sealed override void RaisePostBackEvent(IPostBackEventHandler sourceControl, string eventArgument)
        {
            try
            {
                BeforeEventRaise(sourceControl, eventArgument);
                base.RaisePostBackEvent(sourceControl, eventArgument);
                AfterEventRaise(sourceControl, eventArgument);
            }
            catch (Exception ex)
            {
                if (ex is ThreadAbortException)
                {

                }
                else
                {
                    GlobalCommon.ExceptionProcessor.DoProcess(ex);
                }
            }
        }
        /// <summary>
        /// 当页面事件发生时
        /// </summary>
        /// <param name="sourceControl"></param>
        /// <param name="eventArgument"></param>
        protected virtual void BeforeEventRaise(IPostBackEventHandler sourceControl, string eventArgument)
        {
            //
        }

        /// <summary>
        /// 当页面事件发生之後
        /// </summary>
        /// <param name="sourceControl"></param>
        /// <param name="eventArgument"></param>
        protected virtual void AfterEventRaise(IPostBackEventHandler sourceControl, string eventArgument)
        {
            //
        }

        public override void RegisterRequiresRaiseEvent(IPostBackEventHandler control)
        {
            base.RegisterRequiresRaiseEvent(control);
        }

        public new void RegisterRequiresPostBack(Control control)
        {
            base.RegisterRequiresPostBack(control);
        }
        /// <summary>
        /// 提供给控件进行注册使用
        /// </summary>
        /// <typeparam name="T">Control,IWebControl</typeparam>
        /// <param name="c"></param>
        public void RegisterWebControlDataMap(Control c)
        {
            if (c is IWebDataControl)
            {
                if (_controls_DataMap.ContainsKey(c.ID))
                {
                    _controls_DataMap[c.ID] = c;
                }
                else
                {
                    _controls_DataMap.Add(c.ID, c);
                }
            }
        }
        /// <summary>
        /// 提供给控件进行注册使用
        /// </summary>
        /// <param name="c">Control,IActionPermission</param>
        public void RegisterWebControlPermission(Control c)
        {
            if (c is IActionPermission)
            {
                if (_controls_Permission.ContainsKey(c.ID))
                {
                    _controls_Permission[c.ID] = c;
                }
                else
                {
                    _controls_Permission.Add(c.ID, c);
                }
            }
        }

        public abstract void OnPageLoad();

        protected sealed override void OnInit(EventArgs e)
        {
            try
            {
                base.OnInit(e);
            }
            catch (Exception ex)
            {
                GlobalCommon.ExceptionProcessor.DoProcess(ex);
            }
           
        }
        public sealed override void ProcessRequest(System.Web.HttpContext context)
        {
            try
            {
                base.ProcessRequest(context);
            }
            catch (Exception ex)
            {
               GlobalCommon.ExceptionProcessor.DoProcess(ex);

            }

        }
        
        /// <summary>
        /// 搜索頁面裏面的控件并添加到字典中
        /// </summary>
        /// <param name="contrainer"></param>
        public virtual void FindControls(Control contrainer)
        {
            if (contrainer is ContentPlaceHolder 
                || contrainer.Parent is UpdatePanel 
                || contrainer is Panel
                || contrainer is System.Web.UI.HtmlControls.HtmlGenericControl)
            {
                foreach (Control c in contrainer.Controls)
                {
                    //可能会有某个控件即属于IActionPermission，又属于IWebDataControl
                    if (c is IActionPermission)
                    {
                        RegisterWebControlPermission(c);
                    }

                    if (c is IWebDataControl)
                    {
                        RegisterWebControlDataMap(c);
                    }
                    else if (c is TextBox)
                    {
                        RegisterWebControlDataMap(c);
                    }
                    if (c is Label)
                    {
                        RegisterWebControlDataMap(c);
                    }
                    if (c is DropDownList)
                    {
                        RegisterWebControlDataMap(c);
                    }
                    if (c is RadioButton)
                    {
                        RegisterWebControlDataMap(c);
                    }
                    if (c is RadioButtonList)
                    {
                        RegisterWebControlDataMap(c);
                    }
                    if (c is CalendarInput)
                    {
                        RegisterWebControlDataMap(c);
                    }
                    if (c is CheckBox)
                    {
                        RegisterWebControlDataMap(c);
                    }
                    if (c is CheckBoxList)
                    {
                        RegisterWebControlDataMap(c);
                    }
                    if (c is HiddenField)
                    {
                        RegisterWebControlDataMap(c);
                    }
                    if (c is UpdatePanel)
                    {
                        FindControls(c.Controls[0]);
                    } 
                    if (c is Panel)
                    {
                        FindControls(c);
                    }
                    if (c is System.Web.UI.HtmlControls.HtmlGenericControl)
                    {
                        if (((System.Web.UI.HtmlControls.HtmlGenericControl)c).TagName.ToUpper() == "DIV")
                        {
                            FindControls(c);
                        }
                    }
                    
                }
            }
            else
            {
                foreach (Control c in contrainer.Controls)
                {
                    FindControls(c);
                }
            }
        }

        /// <summary>
        /// 根據PageMapping獲取對應的數據Module,1.0.0.0版本中使用
        /// </summary>
        /// <param name="m">APageMapping</param>
        /// <returns>PageModule</returns>
        public virtual PageModule GetModule(APageMapping m)
        {
            PageModule rtn = new PageModule();
            if (m != null)
            {
                foreach (string cn in m.PageToManageMapping.Keys)
                {
                    if (_controls_DataMap.ContainsKey(m.PageToManageMapping[cn]))
                    {
                        if (_controls_DataMap.ContainsKey(m.PageToManageMapping[cn]))
                        {
                            rtn.SetValue(cn, GetControlValue(_controls_DataMap[m.PageToManageMapping[cn]]));
                        }
                    }
                    else
                    {
                        rtn.SetValue(cn, null);
                    }
                }
            }

            return rtn;
        }
        /// <summary>
        /// 获取本页面的数据Module，1.0.0.1版本中使用
        /// </summary>
        /// <returns></returns>
        public virtual PageModule GetModule()
        {
            PageModule rtn = new PageModule();
            foreach (Control c in _controls_DataMap.Values)
            {
                if (c is IWebDataControl)
                {
                    rtn.SetValue(((IWebDataControl)c).MapDataField, GetControlValue(c));
                }
            }
            return rtn;
        }
        /// <summary>
        /// 根据module的值往页面写数据
        /// </summary>
        /// <param name="module"></param>
        public virtual void SetModuleValue(IModule module)
        {
            foreach (Control c in _controls_DataMap.Values)
            {
                if (c is IWebDataControl)
                {
                    SetControlValue(c, module.GetValue(((IWebDataControl)c).MapDataField));
                }
            }
        }
        /// <summary>
        /// 获取控件的值
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        protected object GetControlValue(Control c)
        {
            object rtn = null;

            if (c is TextBox)
            {
                rtn = ((TextBox)c).Text;
            }
            else if (c is Label)
            {
                rtn = ((Label)c).Text;
            }
            else if (c is DropDownList)
            {
                rtn = ((DropDownList)c).SelectedValue;
            }
            else if (c is RadioButton)
            {
                rtn = ((RadioButton)c).Checked;
            }
            else if (c is RadioButtonList)
            {
                rtn = ((RadioButtonList)c).SelectedValue;
            }
            else if (c is CalendarInput)
            {
                rtn = ((CalendarInput)c).Text;
            }
            else if (c is CheckBox)
            {
                rtn = ((CheckBox)c).Checked;
            }
            else if (c is CheckBoxList)
            {
                string stempvalue = "";
                foreach (ListItem item in ((CheckBoxList)c).Items)
                {
                    if (item.Selected)
                    {
                        stempvalue += stempvalue == "" ? item.Value : "," + item.Value;
                    }
                }
                rtn = stempvalue;
            }
            else if (c is HiddenField)
            {
                rtn = ((HiddenField)c).Value;
            }

            return rtn;
        }

        protected void SetControlValue(Control c, object value)
        {
            if (c is TextBox)
            {
                ((TextBox)c).Text = ComFunc.nvl(value);
            }
            else if (c is Label)
            {
                ((Label)c).Text = ComFunc.nvl(value);
            }
            else if (c is DropDownList)
            {
                string v = ComFunc.nvl(value);
                if (((DropDownList)c).Items.FindByValue(v) != null)
                    ((DropDownList)c).SelectedValue = ComFunc.nvl(value);
            }
            else if (c is RadioButton)
            {
                ((RadioButton)c).Checked = value != null ? bool.Parse(ComFunc.nvl(value)) : false;
            }
            else if (c is RadioButtonList)
            {
                ((RadioButtonList)c).SelectedValue = ComFunc.nvl(value);
            }
            else if (c is CalendarInput)
            {
                if (value is DateTime)
                {
                    ((CalendarInput)c).SelectedDate = DateTimeStd.ParseStd(value).Value;
                }
                else if (value is DateTimeStd)
                {
                    ((CalendarInput)c).SelectedDate = DateTimeStd.ParseStd(value);
                }
                else
                {
                    ((CalendarInput)c).Text = ComFunc.nvl(value);
                }
            }
            else if (c is CheckBox)
            {
                ((CheckBox)c).Checked = value != null ? bool.Parse(ComFunc.nvl(value)) : false;
            }
            else if (c is CheckBoxList)
            {
                string stempvalue = (string)value;
                if (stempvalue != null)
                {
                    List<string> ltemp = new List<string>();
                    string[] splitvalues = stempvalue.Split(',');
                    foreach (string v in splitvalues)
                    {
                        ltemp.Add(v);
                    }
                    foreach (ListItem item in ((CheckBoxList)c).Items)
                    {
                        if (ltemp.Contains(item.Value))
                        {
                            item.Selected = true;
                        }
                    }
                }

            }
            else if (c is HiddenField)
            {
                ((HiddenField)c).Value = ComFunc.nvl(value);
            }
        }

        /// <summary>
        /// 根據PageMapping獲取對應的數據Module
        /// </summary>
        /// <param name="m">APageMapping</param>
        /// <param name="pm">PageModule</param>
        public virtual void SetModuleValue(APageMapping m, IModule pm)
        {
            foreach (string cn in m.ManageToPageMapping.Keys)
            {
                if (_controls_DataMap.ContainsKey(cn))
                {
                    SetControlValue(_controls_DataMap[cn], pm.GetValue(m.ManageToPageMapping[cn]));
                }
            }
        }

        /// <summary>
        /// 添加js script，在页面展现之前运行js
        /// </summary>
        /// <param name="script"></param>
        public void RegisterScript(string script)
        {
            base.ClientScript.RegisterClientScriptBlock(this.GetType(), Guid.NewGuid().ToString(), script, true);
        }
        /// <summary>
        /// 在页面show完后运行js
        /// </summary>
        /// <param name="script"></param>
        public void RegisterScriptAfterPageShow(string script)
        {
            base.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "<script type='text/javascript'>" + script + "</script>");
        }
        /// <summary>
        /// 添加js script并跳转到指定页面
        /// </summary>
        /// <param name="script">js脚本</param>
        /// <param name="toUrl">要跳转的页面，~表示根路径</param>
        public void RegisterScriptAndGoTo(string script, string toUrl)
        {
            if (GlobalCommon.SecurityStrategy.IsValidUrl(toUrl))
            {
                base.ClientScript.RegisterClientScriptBlock(this.GetType(), Guid.NewGuid().ToString(), script + ";location.href='" + toUrl.Replace("~", SiteRootUrl) + "';", true);
            }
            else
            {
                throw new BizException(toUrl + ":Is not valid URL");
            }
            
        }
        /// <summary>
        /// 获取访问站点的URL-根路径，如：Http://xxx:8080/
        /// </summary>
        public string SiteRootUrl
        {
            get
            {
                string basepath = ResolveClientUrl("~");
                return basepath;
            }
        }

        /// <summary>
        /// 将Panel中的内容导出成Excel
        /// </summary>
        /// <param name="p"></param>
        /// <param name="fileName"></param>
        /// <param name="page"></param>
        public void ExportExcel(Control p, string fileName)
        {
            BaseReponse.Clear();
            BaseReponse.BufferOutput = true;
            //设定输出的字符集
            //BaseReponse.Charset = "UTF-8";
            BaseReponse.Charset = "";
            //假定导出的文件名为FileName.xls
            BaseReponse.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
            //BaseReponse.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            BaseReponse.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-7");
            //设置导出文件的格式
            BaseReponse.ContentType = "application/ms-excel";
            //关闭ViewState
            this.EnableViewState = false;

            System.IO.StringWriter stringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter textWriter = new System.Web.UI.HtmlTextWriter(stringWriter);
            p.RenderControl(textWriter);
            //把HTML写回浏览器
            BaseReponse.Write(stringWriter.ToString());
            try
            {
                BaseReponse.End();
            }
            catch(ThreadAbortException tae)
            {
                string a = tae.Message;
            }
            
        }

        /// <summary>
        /// 为PageChanged事件提供一个工具方法，进行数据绑定
        /// </summary>
        /// <typeparam name="T">WebBaseLogic, IQueryByPage</typeparam>
        /// <param name="gv">GridView</param>
        /// <param name="wmp">WebManageParameter</param>
        /// <param name="ma">WebManager</param>
        /// <param name="e">PageChangedEventArgs</param>
        public QueryByPageReturn BindData<T>(PageNavigation pn, GridView gv, WebManageParameter wmp, WebManager ma, ref PageChangedEventArgs e)
            where T : WebBaseLogic, IQueryByPage
        {
            wmp.GoToPage = e.GotoPage;
            wmp.CurrentPage = e.CurrentPage;
            wmp.PageSize = pn.ShowPageSize;
            wmp.OrderBy = e.OrderBy;
            QueryByPageReturn qbpr = ma.QueryByPage<T>(wmp);
            e.CurrentPage = qbpr.CurrentPage;
            e.TotalPage = qbpr.TotalPage;
            e.PageSize = pn.ShowPageSize;
            e.TotalSize = qbpr.TotalCount;
            gv.DataSource = qbpr.DataResult.Value;
            gv.DataBind();

            return qbpr;
        }
    }
}
